import fs from 'fs'
import path from 'path'
import {getAllDatas} from './src/lib'

async function go() {
  const areaData = await getAllDatas()

  const date = new Date()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const fileName = `${date.getFullYear()}-${month < 10 ? '0' : ''}${month}-${
    day < 10 ? '0' : ''
  }${day}.json`
  const filePath = path.join(__dirname, `../data`)

  return new Promise(resolve => {
    fs.mkdir(
      path.join(__dirname, `./data`),
      {
        recursive: true,
      },
      () => {
        //
        const fileData = Buffer.from(JSON.stringify(areaData))

        // 块方式写入文件
        const wstream = fs.createWriteStream(path.join(filePath, fileName))

        wstream.on('open', () => {
          const blockSize = 128
          const nbBlocks = Math.ceil(fileData.length / blockSize)
          for (let i = 0; i < nbBlocks; i++) {
            const currentBlock = fileData.slice(
              blockSize * i,
              Math.min(blockSize * (i + 1), fileData.length)
            )
            wstream.write(currentBlock)
          }

          wstream.end()
        })
        wstream.on('error', err => {
          console.error('文件存储失败：', err)
          resolve(false)
        })
        wstream.on('finish', () => {
          console.log('文件存储成功：', path.join(filePath, fileName))
          resolve(true)
        })
      }
    )
  })
}

go().finally(() => {
  process.exit()
})
